<template>
  <AssetHolderList
      ref="refHolder"
      :columns="columns"
      :load="onLoadHolders"
      :searchForms="searchForms"
      :join-target="onJoinHolders"
      :join-label="joinLabel"
      :comment="comment">
    <template v-slot:bottom>
      <LevelSelectorDialog
          ref="refSelectDlg"
          :load="onLoadJoinHolders"
          :finish-select="onFinishSelect"
          :title="selectTitle"
          :search-forms="searchForms"
          :tag="tag"
          :mode="'MULTI'"
          :root-item="rootItem"
          :level-mode="props.levelMode"
      />
    </template>
  </AssetHolderList>
</template>

<script setup lang="ts">
import {computed, ref} from 'vue'
import {useCurrent} from '@/utils/UseCurrentFunc'
import AssetHolderList from '@/widget/holder/AssetHolderList.vue'
import LevelSelectorDialog from '@/widget/selector/LevelSelectorDialog.vue'
import {msgError, msgInfo} from "@/utils/InfoUtil";

const selectTitle = ref();
const refSelectDlg = ref();
const refHolder = ref();

const props = withDefaults(
    defineProps<{
      tag: string,
      name: string,
      columns: any,
      readonly?: boolean,
      levelMode?: boolean,
      loadHolders?: any,
      joinHolders?: any,
      loadJoinHolders?: any,
      comment?: string,
    }>(),
    {}
)

const {current} = useCurrent(props.name);

const tag = computed(() => {
  return props.tag ? props.tag : '';
})

const joinLabel = computed(() => {
  return props.readonly ? undefined : `加入${tag.value}`;
})

const rootItem = computed(() => {
  return {id: '', name: `${tag.value}列表`};
})

const searchForms = ref([
  {
    type: 'input',
    name: 'name',
    label: ``,
    size: 'default',
    placeholder: `请输入${tag.value}名称`,
    clearable: true,
    value: '',
    defValue: ''
  }
])

const updateTitle = () => {
  if (current() && current().name) {
    refSelectDlg.value?.updateTitle(current().name + ` 加入${tag.value}`)
  } else {
    refSelectDlg.value?.updateTitle(`加入${tag.value}`)
  }
}

const onLoadHolders = async (params: any) => {
  if (props.loadHolders) {
    return props.loadHolders(params)
  }
}

const onLoadJoinHolders = async (params: any) => {
  if (props.loadJoinHolders) {
    return await props.loadJoinHolders(params)
  }
}

const onJoinHolders = () => {
  refSelectDlg.value.select()
  updateTitle()
}

const refresh = async () => {
  await refHolder.value?.refresh();
}

const onFinishSelect = async (items: any) => {
  if (props.joinHolders) {
    const result = await props.joinHolders(items);
    if (result && result.code === 0) {
      msgInfo(`加入${tag.value}成功！`);
      await refHolder.value?.refresh();
    } else {
      msgError(`加入${tag.value}失败！`);
    }
  }
}

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}
</style>
